import { AfterViewInit, Component, Input, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesModalRef } from '@shared/apes/modal';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { RenderDetailComponent } from '@shared/ag-grid-ext/cell-renders/render-detail.component';
import { DatePipe } from '@angular/common';
import { dateFormat } from '../../utils/utils';
import { ApesDrawerRef } from '@shared/apes/drawer/apes-drawer-ref';


@Component({
  selector: 'drawer-vehicleMasterControl',
  templateUrl: './drawer-vehicleMasterControl.component.html',
  styleUrls: ['./style/index.scss'],
})
export class DrawerVehicleMasterControlComponent implements OnInit, AfterViewInit {
  model: any = {};
  options: any;
  resultsData: any = [];


  body: any = {};

  @Input() api: any;
  @Input() data: any;
  id: string;

  gridPanels: any[];

  /** grid 相关 **/
  private gridApi;
  private gridColumnApi;
  frameworkComponents: any;
  modules: Module[] = AllModules;
  localeText: any;
  detailCellRendererParams: any;
  defaultColDef: any;
  gridOptions: GridOptions;
  rowModelType: any;
  isRowMaster: any;
  detailCellRenderer: any;
  domLayout: any = 'autoHeight';

  /** data 相关 **/
  carInfo: any = {};
  pickCarInfo: any = {};
  deliverInfoFoot: any[];

  constructor(
    private drawerRef: ApesDrawerRef<string>,
    private apiService: ApiService,
    protected expressionService: ExpressionService,
    private datePipe: DatePipe,
    private gridConfigService: GridConfigService,
  ) {
    this.gridPanels = [
      {
        name: '接车信息', id: 'pick_car_info', active: true, rowData: [], columnDefs: [
          { headerName: '接车日期', field: 'PICK_DATE', width: 220, cellRenderer: this.toDate },
          { headerName: '接车员', field: 'P_UID', width: 220 },
          { headerName: '进店里程', field: 'MILEAGE', width: 220 },
          { headerName: '接车类型', field: 'PICK_TYPE', width: 220 },
          { headerName: '预计交车日期', field: 'ESTIMATE_DATE', width: 220 },
          { headerName: '交车日期', field: 'TIME', width: 220 },
          { headerName: '交车人', field: 'U_NAME', width: 220 },
          { headerName: '交车备注', field: 'ADVANCE_REMARK', width: 220 },
        ],
      },
      {
        name: '方案明细', id: 'wait_confirm', active: true, rowData: [], columnDefs: [
          // { headerName: '方案号', field: 'plan_id', width: 220, cellRenderer: 'agGroupCellRenderer' },
          { headerName: '方案号', field: 'plan_id', width: 220 },
          { headerName: '方案状态', field: 'plan_state', width: 220 },
          { headerName: '方案创建时间', field: 'plan_create_date', width: 220 },
          { headerName: '方案确认时间', field: 'confirm_date', width: 220 },
          { headerName: '方案结算时间', field: 'plan_receivable_date', width: 220 },
          { headerName: '结算人', field: 'clerk_id', width: 220 },
          // { headerName: '待办节点', field: 'plan_point', width: 220 },
          // { headerName: '预计完成时间', field: 'es_date', width: 220, cellRenderer: this.toDate },
        ],
      },
      {
        name: '施工明细', id: 'wait_work', active: true, rowData: [], columnDefs: [
          { headerName: '方案号', field: 'plan_id', width: 220 },
          { headerName: '商品', field: 'product_name', width: 220 },
          { headerName: '数量', field: 'qty_sale', width: 220 },
          { headerName: '服务方', field: 'service_side_name', width: 220 },
          { headerName: '工单状态', field: 'mian_state', width: 220 },
          // { headerName: '单据状态', field: 'mten_state', width: 220 },
          { headerName: '排位时间', field: 'main_rank_date', width: 220 },
          // { headerName: '施工状态', field: 'mten_work_state', width: 220 },
          { headerName: '施工耗时', field: 'work_time', width: 220 },
          { headerName: '完工时间', field: 'work_finish_date', width: 220 },
          { headerName: '施工人员', field: 'mten_worker', width: 220 },
          { headerName: '质检状态', field: 'test_state', width: 220 },
          { headerName: '质检通过时间', field: 'test_date', width: 220 },
          { headerName: '质检员', field: 'test_uname', width: 220 },
        ],
      },
      {
        name: '配件领用明细', id: 'wait_prduct', active: true, rowData: [], columnDefs: [
          { headerName: '方案号', field: 'plan_id', width: 220 },
          { headerName: '商品', field: 'product_name', width: 220 },
          { headerName: '单位', field: 'uom_name', width: 220 },
          { headerName: '可领用', field: 'usable_qty', width: 220 },
          { headerName: '已领用', field: 'qty_receive', width: 220 },
          { headerName: '库存位置', field: 'location_name', width: 220 },
        ],
      },
      {
        name: '要货明细', id: 'wait_need', active: true, rowData: [], columnDefs: [
          { headerName: '方案号', field: 'plan_id', width: 220 },
          { headerName: '商品', field: 'product_name', width: 220 },
          { headerName: '单位', field: 'uom_name', width: 220 },
          { headerName: '要货数', field: 'qty_require', width: 220 },
          { headerName: '已分配数', field: 'qty_assigned', width: 220 },
          { headerName: '终止数', field: 'qty_end', width: 220 },
          { headerName: '已到货数', field: 'qty_arrive', width: 220 },
          { headerName: '采购平台', field: 'plant_name', width: 220 },
        ],
      },
      // {
      //   name: '总检', id: 'wait_test', active: true, rowData: [], columnDefs: [
      //     { headerName: '方案号', field: 'plan_id', width: 220, cellRenderer: 'agGroupCellRenderer' },
      //     { headerName: '商品', field: 'product_name', width: 220 },
      //     { headerName: '数量', field: 'qty_sale', width: 220 },
      //     { headerName: '质检状态', field: 'test_state', width: 220 },
      //     { headerName: '质检时间', field: 'test_date', width: 220, cellRenderer: this.toDate },
      //     { headerName: '质检员', field: 'test_uname', width: 220 },
      //   ],
      // },
      // {
      //   name: '结算', id: 'wait_money', active: true, rowData: [], columnDefs: [
      //     { headerName: '方案号', field: 'plan_id', width: 220 },
      //     { headerName: '金额', field: 'plan_amount', width: 220 },
      //     { headerName: '状态', field: 'plan_state', width: 220 },
      //     { headerName: '结算时间', field: 're_date', width: 220, cellRenderer: this.toDate },
      //     { headerName: '结算人', field: 're_uname', width: 220 },
      //   ],
      // },
    ];
  }

  ngAfterViewInit(): void {
    this.getData();
  }


  ngOnInit() {
    this.gridPanels.forEach((grid) => {
      grid['gridOptions'] = <GridOptions>{
        suppressExcelExport: true,
        suppressCsvExport: true,
        showToolPanel: false,
      };
      grid.gridOptions.localeText = this.gridConfigService.getLocaleText();
      grid['defaultColDef'] = { flex: 1 };
      grid['detailCellRendererParams'] = {
        detailGridOptions: {
          columnDefs: [
            { headerName: '商品', field: 'product_name', width: 220 },
            { headerName: '数量', field: 'qty_sale', width: 100 },
          ],
        },
        getDetailRowData: function(params) {
          params.successCallback(params.data);
        },
      };
      grid['rowModelType'] = 'clientSide';
      grid['frameworkComponents'] = { detail: RenderDetailComponent };
      grid['detailCellRenderer'] = 'detail';
      grid['isRowMaster'] = (dataItem) => {
        if (dataItem && dataItem.hasOwnProperty('detailList')) {
          return dataItem.detailList.length > 0;
        } else {
          return false;
        }
      };
    });
  }

  getData() {
    this.id = this.data.id;
    const data = { node: this.data.node, ...this.data };
    this.apiService.post(this.api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        console.log('车辆状态详情', body);
        if (body) {
          this.carInfo = body['car_info'];
          this.pickCarInfo = body['pick_car_info'];
          this.deliverInfoFoot = body['deliver_info_foot'];
          this.gridPanels.forEach((grid) => {
            let key = grid.id;
            if (body.hasOwnProperty(key)) {
              if (key == 'pick_car_info') {
                grid.rowData = [body[key]];
              } else {
                grid.rowData = body[key];
              }
            }
          });
        }

      });
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
  }

  gridHeight(panel) {
    let height: any = 0;
    if (panel.rowData.length > 0) {
      if (panel.id == 'pick_car_info') {
        height = '65px';
      } else {
        height = '250px';
      }
    }
    return height;
  }

  timesChange(times: number) {
    let time;
    if (times) {
      time = this.datePipe.transform(new Date(times), 'yyyy-MM-dd HH:mm:ss');
    } else {
      time = '';
    }
    return time;
  }

  toDate(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    let time;
    if (data == undefined) {
      time = '--';
    } else {
      time = dateFormat('yyyy-MM-dd HH:mm:ss', new Date(data));
      // time = this.datePipe.transform(new Date(data), 'yyyy-MM-dd HH:mm:ss');
    }
    return time;
  }

  close(): void {
    this.drawerRef.close(this.data);
  }

}
